feat(net): add isPortAvailable#7204
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #7204 +/- ##
========================================
Coverage 94.83% 94.84%
========================================
Files 617 618 +1
Lines 51674 51438 -236
Branches 9350 9305 -45
========================================
- Hits 49007 48785 -222
+ Misses 2121 2112 -9
+ Partials 546 541 -5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Great work! Looks good to me, Thanks. I'd go for keeping this one small at this time. |
| using _listener = Deno.listen({ | ||
| port, | ||
| hostname: options?.hostname ?? "0.0.0.0", | ||
| }); |
There was a problem hiding this comment.
Seems like "0.0.0.0" is already the default in Deno.ListenOptions.
| using _listener = Deno.listen({ | |
| port, | |
| hostname: options?.hostname ?? "0.0.0.0", | |
| }); | |
| using _listener = Deno.listen({ port, hostname: options?.hostname }); |
There was a problem hiding this comment.
Good catch. The literal hostname: options?.hostname trips exactOptionalPropertyTypes (passing hostname: undefined is not assignable to hostname?: string), so I forward the hostname only when it is set and otherwise omit it, letting Deno.ListenOptions apply its 0.0.0.0 default:
using _listener = Deno.listen(
options?.hostname !== undefined
? { port, hostname: options.hostname }
: { port },
);That drops the redundant literal without widening what gets forwarded to Deno.listen. Updated in the latest push.
1e1db52 to
8b01f2b
Compare
8b01f2b to
c996483
Compare
Closes #7196.
@std/netonly hadgetAvailablePort, so there was no quick way to ask "is this specific port free?" without writing theDeno.listenplus catch yourself. This adds that:It returns
truewhen the TCP port can be listened on,falseonDeno.errors.AddrInUse, and rethrows any other error (includingPermissionDeniedfor privileged ports or a missingnetpermission).hostnamedefaults to0.0.0.0. Sincenetis stable, it lives inunstable_is_port_available.tsas the@std/net/unstable-is-port-availableexport and isn't re-exported frommod.ts.The doc comment is upfront about the obvious race: the port can be taken between the check and your own
listen, so it points back toport: 0/getAvailablePortfor cases where you own the listener.Tests cover an available port, a port already in use, the
hostnameoption, and the rethrow path for errors other thanAddrInUse.deno task lint,deno fmt --check, anddeno test -A --docpass locally.One open question: happy to also add
getAvailablePorts(count, options?)here if that would be useful, or keep this PR to the single function.